<?php
require('init.php');
$title = 'INscripcion';
require(LIBWWWDIR . '/header.php');

//variables para spans
$classTeam = "noshow";
$classUser1 = "noshow";
$classUser2 = "noshow";
$classUser3 = "noshow";
$CampoFalse = "Sólo caracteres alfanuméricos o guión bajo.(Mínimo 3)";
$userFalse = "Usuario no registrado";
$userInTeam = "El usuario ya pertenece a otro team";

function validateUsername($user){
if( strlen($user) < 3 )
	return false;
elseif( !preg_match("/^\w+$/", $user ) )
	return false;
else
	return true;
}
function checkTeamname( $teamname ){
	$conexion = connect();
	$query = "SELECT teamname FROM ins_nat_contest WHERE teamname = '".$teamname ."'";
	$res = mysql_query($query, $conexion) or die(mysql_error());
	$exit_team = mysql_fetch_array($res, MYSQL_NUM);
	$tam_res = mysql_num_rows($res);
	if( $tam_res == 0 )
		return true; // teamname disponible
	else
		return false; // teamname no disponible
}
function checkUsername( $user ){
	$conexion = connect();
	$query = "SELECT username FROM users WHERE username = '".$user ."'";
	$res = mysql_query($query, $conexion) or die(mysql_error());
	$exit_user = mysql_fetch_array($res, MYSQL_NUM);
	$tam_res = mysql_num_rows($res);
	if( $tam_res == 1 )
		return true; // user existente
	else
		return false; // user no existente
}
//verificar que el usuario no este inscrito con otro equipo
function checkUserTeam( $user ){
	$conexion = connect();
	$query = "SELECT members FROM ins_nat_contest ";
	$res = mysql_query($query, $conexion) or die(mysql_error());
	$exit_team = mysql_fetch_array($res, MYSQL_NUM);
	$tam_res = mysql_num_rows($res);
	print_r($exit_team);
	for( $i=0; $i<$tam_res; $i++ ){
		$users = explode(",",$exit_team[$i]);
		for($j=0; $j<count($users); $j++){
			if( $users[$j] == $user )
				return false;
		}
	}
	return true;
}
function igual1($val){
	if( $val == '0' )
		return false;
	elseif( $val == '2' )
		return false;
	else
		return true;
}
/*function generarLogin( $nameteam ){
mt_srand (time());
	$numero_aleatorio = mt_rand(0,1000); 
	$sub = substr($nameteam, 0, 3);
	$log=$sub.$numero_aleatorio;
	return $log;
}*/

if( isset($_POST['submit']) ){
	if ( isset($_POST['teamname']) ){
		$teamname = $_POST['teamname'];
		if( validateUsername($teamname) ){ 	//validar el campo teamname
			if( checkTeamname( $teamname ) ){	//verificar existencia teamname
				$team = '1'; //teamname disponible 
			}else{
				$team = '2'; //teamname no disponible
				$classTeam = "error_val";
				$mssgTeam = "El team ya existe debes elegir otro nombre";
			}
		}else{
			$team = '0';//campo no valido
			$classTeam = "error_val";
			$mssgTeam = $CampoFalse;
		}	
	}
	if ( isset($_POST['user1']) ){
		$user_name1 = $_POST['user1'];
		if( validateUsername($user_name1) ){ 	//validar el campo
			if( checkUsername( $user_name1 ) ){	//verificar existencia usuario
				//FALTA VALIDAR USERS IN TEAMS
				//if( checkUserTeam($user_name1) ){
					$user1 = '1'; /*user existente y NO perteneciente a otro equipo*/
				/*}else{
					$user1 = '3'; //user no existente
					$classUser1 = "error_val";
					$mssgUser1 = $userInTeam;
				}*/
			}else{
				$user1 = '2'; //user no existente
				$classUser1 = "error_val";
				$mssgUser1 = $userFalse;
			}
		}else{
			$user1 = '0';//campo no valido
			$classUser1 = "error_val";
			$mssgUser1 = $CampoFalse;
		}	
	}
	if ( isset($_POST['user2']) ){
		$user_name2 = $_POST['user2'];
		if( validateUsername($user_name2) ){ 	
			if( checkUsername( $user_name2 ) ){	
				$user2 = '1';  
			}else{
				$user2 = '2'; 
				$classUser2 = "error_val";
				$mssgUser2 = $userFalse;
			}
		}else{
			$user2 = '0';
			$classUser2 = "error_val";
			$mssgUser2 = $CampoFalse;
		}	
	}
	if ( isset($_POST['user3']) ){
		$user_name3 = $_POST['user3'];
		if( validateUsername($user_name3) ){ 	
			if( checkUsername( $user_name3 ) ){	
				$user3 = '1'; 
			}else{
				$user3 = '2';
				$classUser3 = "error_val";
				$mssgUser3 = $userFalse; 
			}
		}else{
			$user3 = '0';
			$classUser3 = "error_val";
			$mssgUser3 = $CampoFalse;
		}	
	}
	//if( igual1($team) && igual1($user1) && igual1($user2)  && igual1($user3) ){
		$members = $_POST['user1'].", ".$_POST['user2'].", ".$_POST['user3'];
		$user = $_POST['user1'];
		//$members = $user_name1." ,".$user_name2." ,".$user_name3;
		$login = generarLogin($teamname);
		$hora = now();
		$conexion = connect();		
		$query = "INSERT INTO ins_nat_contest (username, cid, teamname, members, date) 
			values('$user', '$cid', '$teamname', '$members', '$hora')";
		$res = mysql_query($query, $conexion) or die(mysql_error());
		if($res){
			$all_ok = "1";
			//echo "Se ha guardado con exito!!!!!!!!!!!<br>";
		}else{
			$all_ok  = "0" ;
			//echo "chanflee!! :S <br>";
		} 
		if( $all_ok == "1" ){
			echo '<script type="text/javascript" >'.
			'alert("Inscripción exitosa. PRONTO RECIBIRAS DATOS DE LOGEO ");'.
			'</script>';
		}else{
			echo '<script type="text/javascript" >'.
			'alert("Error en la inscripcción ");'.
			'</script>';
		}
	
	 //}
	
}
///******************************************************************************
/// verificar que en members exista un usuario igual al contest que esta logeado(que está haciendo la inscripción)
///******************************************************************************
if( !isset($_GET['c']) && !(isset($_POST['submit'])) ){
	header('Location: index.php');
	//echo "regresar al index";
}

$cid = $_GET['c'];

$res = $DB->q('TABLE SELECT contestname, categoryid FROM contest WHERE cid = %i',$cid );
$name = $res[0]['contestname'];

require(LIBWWWDIR . '/forms.php'); ?>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
<script type="text/javascript" src="../jquery-validation-1.9.0/lib/jquery.js" charset="utf-8"></script>
<script type="text/javascript" src="../jquery-validation-1.9.0/jquery.validate.js" charset="utf-8"></script>
<script type="text/javascript" src="../jquery-validation-1.9.0/jquery.validate.min.js" charset="utf-8"></script>
<script type="text/javascript" src="../jquery-validation-1.9.0/additional-methods.js" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#insc").validate({
	rules:{
		ciudad : {
            		required: function(element) {
                return $("#ciudad").val() == '';
            	}},
		teamname :{ minlength: 3, alphanumeric: true, required: true },
		user1:{ minlength: 3, alphanumeric: true, required: true},
		user2:{ minlength: 3, alphanumeric: true, required: false},
		user3:{minlength: 3, alphanumeric: true, required: false}
	},
	});
});
</script>
<link rel="stylesheet" href="../style.css" media="screen">
</head>
<body>
<h3>Inscripción al contest: <?php echo $name?></h3>
<p>Los integrantes del equipo deben ser usuarios registrados</p>
<?php
echo addForm('form3.php','post','insc');
?>
<table style="border: 1px solid #9f9f9f;" cellspacing="10">	
<tr><td><label for="teamname">Nombre del equipo:</td>
<td><input id="teamname" type="text" name="teamname" value="<?php echo $teamname?>"/><br>
<span class="<?php echo $classTeam?>" style="color: red; font-size: 10pt" ><?php echo $mssgTeam?></span>
</td></tr>
<tr><td><label for="integ">Integrantes<br></td></tr>
<tr><td><label for="user1">Username 1<br></td><td>
<input id="user1" type="text" name="user1" value="<?php echo $user_name1?>"/>
<span class="<?php echo $classUser1?>" style="color: red; font-size: 10pt" ><?php echo $mssgUser1?>
</span><br></td></tr>
<tr><td><label for="user2">Username 2<br></td><td>
<input id="user2" type="text" name="user2" value="<?php echo $user_name2?>"/><br>
<span class="<?php echo $classUser2?>" style="color: red; font-size: 10pt" ><?php echo $mssgUser2?>
</span></td></tr>
<tr><td><label for="user3">Username 3<br></td><td>
<input id="user3" type="text" name="user3" value="<?php echo $user_name3?>"/>
<span class="<?php echo $classUser3?>" style="color: red; font-size: 10pt" ><?php echo $mssgUser3?>
</span><br></td></tr>
</table>
<tr><td><label for="submit"></td><td>
<?php echo addSubmit('Inscribir', 'submit', "insc.submit()"); ?></td></tr>
<?php
echo addEndForm();
?>
</body>
</html>
